import CryptoJS from 'crypto-js'
import JSEncrypt from 'jsencrypt'

let publicKey = '这里写你的公钥'

export function getRandomKeyIv() {
	let key = CryptoJS.lib.WordArray.random(8)
	return key.toString(CryptoJS.enc.Hex)
}

/**
 * AES加密 ：字符串 key iv  返回base64
 * @param word 加密文本
 * @param keyStr 秘钥
 * @param ivStr 偏移量
 * @return {string}
 */
export const Encrypt = (word: any, keyStr: string, ivStr: string): any => {
	if (!keyStr && ivStr) return word
	word = typeof word === 'string' ? word : JSON.stringify(word)
	const key = CryptoJS.enc.Utf8.parse(keyStr)
	const iv = CryptoJS.enc.Utf8.parse(ivStr)
	const src = CryptoJS.enc.Utf8.parse(word)
	const encrypted = CryptoJS.AES.encrypt(src, key, {
		iv: iv,
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.ZeroPadding
	})
	return encrypted.toString()
}

/**
 * AES 解密 ：字符串 key iv  返回base64
 * @param word 加密文本
 * @param keyStr 秘钥
 * @param ivStr 偏移量
 * @return {string}
 */
export const Decrypt = (word: any, keyStr: string, ivStr: string): any => {
	if (!keyStr && ivStr) return word
	const key = CryptoJS.enc.Utf8.parse(keyStr)
	const iv = CryptoJS.enc.Utf8.parse(ivStr)
	const decrypt = CryptoJS.AES.decrypt(word, key, {
		iv: iv,
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.ZeroPadding
	})
	return JSON.parse(CryptoJS.enc.Utf8.stringify(decrypt))
}

// 非对称加密数据
const crypt = new JSEncrypt()
crypt.setPublicKey(publicKey)

export function encryptedData(data: any) {
	if (typeof data !== 'string') {
		data = JSON.stringify(data)
	}
	return crypt.encrypt(data)
}

const md5 = (data: any) => {
	return CryptoJS.MD5(data).toString()
}
/**
 * 签名
 * @param appId appid
 * @param nonce 随机值
 * @param timestamp 签名时间戳
 * @param data 数据
 */
export const getSign = (appId: any, nonce: any, timestamp: any, data: any) => {
	let signSrc = appId + nonce + timestamp
	let rstObj = {}
	if (data) {
		let arr = Object.keys(data)
		for (let key of arr.sort()) {
			rstObj[key] = data[key]
		}
		signSrc = signSrc + JSON.stringify(rstObj)
	}
	return md5(signSrc)
}
